"""
@Project ：HaloTeachingPro 
@File    ：ReadExcelFileUtil.py
@IDE     ：PyCharm 
@Author  ：ceiling
@Date    ：2025/4/13 11:39 
"""
import openpyxl
from pathlib import Path


class ReadExcelFileUtil:

    @classmethod
    def load_excel_data_as_tuples(cls, excel_path, sheet_name=None, *fields):
        """
        读取 Excel 文件并转换为适合 pytest 参数化的列表元组格式 [(...), (...)]

        :param excel_path: Excel 文件路径
        :param sheet_name: 指定 sheet 名，默认第一个
        :param fields: 你希望提取的字段名（标题行的字段）
        :return: list[tuple]
        """
        excel_file = Path(excel_path)
        if not excel_file.exists():
            raise FileNotFoundError(f"Excel 文件不存在: {excel_path}")

        wb = openpyxl.load_workbook(excel_file)
        sheet = wb[sheet_name] if sheet_name else wb.active

        # 获取表头
        headers = [cell.value for cell in next(sheet.iter_rows(min_row=1, max_row=1))]

        # 字段索引列表
        if not fields:
            # 如果不传 fields，默认用全部字段
            fields = headers
        field_indexes = [headers.index(f) for f in fields]

        result = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            row_data = tuple(row[i] for i in field_indexes)
            result.append(row_data)

        return result
